import { Component, OnInit , ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {MatDialog} from '@angular/material';
import {NewTaskComponent} from '../new-task/new-task.component';
import {CopyTaskComponent} from '../copy-task/copy-task.component';
import {ConfirmDialogComponent} from '../../share/confirm-dialog/confirm-dialog.component';
import {NewTaskListComponent} from '../new-task-list/new-task-list.component';
import {ActivatedRoute} from '@angular/router';
import {Store, select} from '@ngrx/store';
import * as actions from '../../actions/task-list.action';
import * as taskActions from '../../actions/task.action';
import * as fromRoot from '../../reducers';
import { TaskList } from 'src/app/domain';
import { Observable } from 'rxjs';
import {map, filter, take, pluck , switchMap, withLatestFrom} from 'rxjs/operators';
@Component({
  selector: 'app-task-home',
  templateUrl: './task-home.component.html',
  styleUrls: ['./task-home.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TaskHomeComponent implements OnInit {
  /* lists = [
    {
      id:1,
      order:1,
      name:'代办',
      tasks:[
        {
          id:1,
          desc:'任务一：去星巴525252452克买咖啡',
          completed:true,
          priority:3,
          owner:{
            id:1,
            name:'张三',
            avatar:'people1'
          },
          reminder:new Date(),
          dueDate:new Date(),
        },
        {
          id:2,
          desc:'任务2：5456465',
          completed:true,
          priority:2,
          owner:{
            id:1,
            name:'ytu',
            avatar:'people2'
          },
          reminder:new Date(),
          dueDate:new Date(),
        },
        {
          id:3,
          desc:'任务3：5456465',
          completed:true,
          priority:1,
          owner:{
            id:1,
            name:'ytu',
            avatar:'people2'
          },
          reminder:new Date(),
          dueDate:new Date(),
        },
      ]
    },
    {
      id:2,
      order:2,
      name:'78',
      tasks:[
        {
          id:1,
          desc:'任务一：5456465',
          completed:true,
          priority:1,
          owner:{
            id:1,
            name:'ytu',
            avatar:'people2'
          },
          reminder:new Date(),
          dueDate:new Date(),
        },
      ]
    },
  ]
*/
projectId$: Observable<string>;
lists$: Observable<any>;
constructor(
    private dialog:MatDialog,
    private cd:ChangeDetectorRef,
    private route:ActivatedRoute,
    private store$:Store<fromRoot.State>
  ) { 
    this.projectId$ = this.route.paramMap.pipe(
      map(p=> {
        console.log(p);
        return p.get('id')})
    );
    this.projectId$.subscribe(d=>console.log(d))
    this.lists$ = this.store$.pipe(select(fromRoot.getTasksByLists));
  }

  ngOnInit() {
  }
  launchNewTaskDialog(list){
    const user$ = this.store$.pipe(
      select(fromRoot.getAuthState),
      map(auth=>{console.log(auth);return auth.user}),
      take(1),
      map(user=>this.dialog.open(NewTaskComponent,{data:{title:'新建任务',owner:user}})),
      switchMap(dialogRef=>dialogRef.afterClosed()),
      take(1),
      filter(n=>n)
    ).subscribe(val=>this.store$.dispatch(new taskActions.AddAction({...val, taskListId: list.id, completed: false,createDate:new Date()})))
  }
  launchCopyTaskDialog(list){
     this.lists$.pipe(
       map(l=>l.filter(n=>n.id!==list.id)),
       map(li=>this.dialog.open(CopyTaskComponent,{data:{lists:li}})),
       switchMap(dialogRef=> dialogRef.afterClosed()),
       take(1),
       filter(n=>n)
     ).subscribe(val=>this.store$.dispatch(new taskActions.MoveALLAction({srcListId:list.id,targetListId:val})))
    // const dialogRef = this.dialog.open(CopyTaskComponent,{data:{lists:this.lists}});
  }
  launchUpdateTaskDialog(task){
    const dialogRef = this.dialog.open(NewTaskComponent,{data:{title:'修改任务',task:task}});
    dialogRef.afterClosed().pipe(
      take(1),
      filter(n => n)
    ).subscribe(val => this.store$.dispatch(new taskActions.UpdateAction({...task,...val})))
  }
  launchConfirmDialog(list: TaskList) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent,{data:{title:'提示',content:'你确认删除该任务列表吗?'}});
    dialogRef.afterClosed().pipe(
      take(1),
      filter(n => n)
    )
    .subscribe(
      result => {
        console.log(result);
        return this.store$.dispatch(new actions.DeleteAction(list))
      }
      );
  }
  launchEditListDialog(list: TaskList) {
    const dialogRef = this.dialog.open(NewTaskListComponent, {data: {title: '更改列表名称', taskList: list}});
    dialogRef.afterClosed().pipe(
      take(1)
    )
    .subscribe(result => this.store$.dispatch(new actions.UpdateAction({...result,id:list.id})));
  }
  launchNewListDialog(ev:Event){
    const dialogRef = this.dialog.open(NewTaskListComponent,{data:{title:'新建列表',}});
    dialogRef.afterClosed().pipe(
      take(1),
      withLatestFrom(this.projectId$,(val,projectId)=>({...val, projectId: projectId}))
    ).subscribe(result=> this.store$.dispatch(new actions.AddAction(result)));
  }
  handleMove(srcData,list){
    switch(srcData.tag){
      case 'task-item':
        console.log('handling item');
        break;
      case 'task-list':
        console.log('handling list');
        const srcList = srcData.data;
        const tempOrder = srcList.order;
        srcList.order = list.order;
        list.order = tempOrder;
    }
  }
  handleQuickTask(desc:string,list){
    const user$ = this.store$.pipe(
      select(fromRoot.getAuthState),
      map(auth => {console.log(auth);return auth.user}),
      take(1)
    ).subscribe(user =>this.store$.dispatch(new taskActions.AddAction({
      desc: desc,
      priority: 3,
      taskListId: list.id,
      ownerId: user.id,
      completed: false,
      participantIds: []
    } as any)));
  }
}
